import colorCofig from "@/config/color.js"
import config from "@/config/config.js"
import storage from "@/uni-sub-base/utils/storage.js"
import { getCartTotal, getSupplierCartTotal } from "@/utils/cartUtil.js"
import { mapState, mapMutations, mapGetters } from "vuex"
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js"
import MescrollMoreItemMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mixins/mescroll-more-item.js"
import { getNavigationBarTitle, getUrlTarget } from "@/uni-sub-base/utils/utils.js"
import { pagetackinfo } from "@/uni-sub-base/module/gather/util.js"
import gatherType from "@/uni-sub-base/module/gather/type.js"
import { getShopUrls } from "@/utils/appUrls.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
import { eventBus } from "@/utils/eventBus.js"
import { GetGuideApiUrl } from "@/service/api/web.js"
export default {
    mixins: [MescrollMixin, MescrollMoreItemMixin], // 注意此处还需使用MescrollMoreItemMixin (必须写在MescrollMixin后面)
    data() {
        return {
            //设置默认的分享参数
            share: {
                title: "",
                path: "/pages/index/index",
                imageUrl: "",
                desc: "",
                content: "",
            },
            downOption: {
                use: false,
            },
            upOption: {
                page: {
                    num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
                    size: 10, // 每页数据的数量
                    time: null, // 加载第一页数据服务器返回的时间; 防止用户翻页时,后台新增了数据从而导致下一页数据重复;
                },
                textLoading: "加载中 ...", // 加载中的提示文本
                textNoMore: "-- 没有更多了 --", // 没有更多数据的提示文本
                empty: {
                    use: true, // 是否显示空布局
                    icon: "/static/img/empty.png", // 图标路径 (建议放入static目录, 如 /static/img/mescroll-empty.png )
                    tip: "~ 暂无数据 ~", // 空提示
                },
                toTop: {
                    src: false,
                },
            },
            listEmpty: {
                icon: "/static/img/empty.png", // 图标路径 (建议放入static目录, 如 /static/img/mescroll-empty.png )
                tip: "~ 暂无数据 ~", // 空提示
            },
            tackParam: {
                startTime: "",
                pageTitle: "",
                urlTarget: "",
            },
            setCartData: [],
            setSupplierCartData: [],
            isChangeCart: false,
            themeColor: "",
        }
    },
    onLoad(e) {
        //判断登录状态
        // let token = this.getToken
        // if (!token || token == '') {
        // 	//未登录
        // 	let pages = getCurrentPages();
        // 	let route = pages[pages.length - 1].route;
        // 	if (!route.includes('pages/login')) {
        // 		this.appCheckIsLogin()
        // 	}
        // }
        this.initTack()
        this.getThemeColorFn()
    },
    onUnload() {
		// this.tackVisit()
    },
    computed: {
        ...mapGetters(["getSupplierCartData", "getToken", "getThemeColor"]),
        ...mapState([
            "networkType"
        ])
    },
    methods: {
        ...mapMutations(["SET_AUTH", "SET_THEME_COLOR","SET_APIURL"]),
		async GetGuideApi(){
            if(this.networkType != 'none'){
                let pram = '?businessNo='+config.businessId
                await GetGuideApiUrl(pram).then((res) => {
                    if (res.State==1) {
                        this.SET_APIURL(res.Data)
                    }else{
                        uni.showToast({
                            title: res.Msg,
                            icon: "none",
                            duration: 2000,
                        })
                    }
                })
            }
		},
        getThemeColorFn() {
            this.themeColor = "--themeColor:" + this.getThemeColor
        },
        setStatusBarStyle(style) {
            this.$nextTick(() => {
                uni.setNavigationBarColor({
                    frontColor: style == "dark" ? "#000000" : "#ffffff",
                    backgroundColor: "#000000",
                })
            })
        },
        h5Init() {
            let themeColor = storage.getCache("themeColor")
            if (themeColor) {
                this.SET_THEME_COLOR(themeColor)
            }
        },
		
        appCheckIsLogin() {
            // //判断登录状态
            // let token = storage.getCache("token")
            // if (!token || token == '') {
            // 	uni.reLaunch({
            // 		url: "/pages/login/loading"
            // 	});
            // }else{
            // 	this.SET_AUTH(token)
            // }
        },
        getAppSet() {
            let productDisplay = storage.getCache("productDisplay")
            if (productDisplay) {
                let appSet = config.appSet
                appSet.isHideImg = productDisplay.IsShowImg == 0
                appSet.isHideProDetail = productDisplay.IsShowImg == 0
                appSet.IsShowConversionRate = productDisplay.IsShowConversionRate
                appSet.IsShowRemark = productDisplay.IsShowRemark
                appSet.IsShowSkuList = productDisplay.IsShowSkuList
                appSet.NoCheckStock = productDisplay.NoCheckStock
                appSet.PriceDecimalPlaces = productDisplay.PriceDecimalPlaces
                return appSet
            }
            return config.appSet
        },
		getUseUrl(){
			return config.useUrl
		},
        getAppId() {
            let appSet = config.appSet
            if (appSet.appIds) {
                if (getPlatform() == "android") {
                    return appSet.appIds.android ? appSet.appIds.android : ""
                }
                if (getPlatform() == "ios") {
                    return appSet.appIds.ios ? appSet.appIds.ios : ""
                }
            }
            return ""
        },
        // 获取商城模式
        getSupplierMode() {
            let webInfo = storage.getCache("webInfo")
            let supplierMode = -1
            if (webInfo) {
                supplierMode = webInfo.SupplierMode || 0
            }
            return supplierMode
        },
        //处理为供应商数据格式
        formatSupplierCart(datas) {
            if (!datas || datas.length < 1) {
                return []
            }
            let supplierItems = []
            //同一供应商归总
            datas.forEach((e) => {
                let supplierFilterItem = supplierItems.filter((item) => {
                    return item.SupplierId == e.SupplierId
                })
                if (supplierFilterItem.length < 1) {
                    let ProductItems = []
                    ProductItems.push(e)
                    let obj = {
                        SupplierName: e.SupplierName,
                        SupplierId: e.SupplierId,
                        ProductId: e.ProductId,
                        V_Title: e.V_Title,
                        V_ThumbnailUrl160: e.V_ThumbnailUrl160,
                        ProductItems: ProductItems,
                    }
                    supplierItems.push(obj)
                } else {
                    supplierFilterItem[0].ProductItems.push(e)
                }
            })
            return supplierItems
        },
        //更新购物车角标
        easyUpTabBarBadge(data, callBack) {
            getCartTotal(data, (res) => {
                if (callBack) {
                    callBack(res.totalSpace)
                }
            })
        },
        // 获取商城模式
        getSupplierMode() {
            let webInfo = storage.getCache("webInfo")
            let supplierMode = -1
            if (webInfo) {
                supplierMode = webInfo.SupplierMode || 0
            }
            return supplierMode
        },
        //是否需要报价
        ApplySupplierPirce() {
            let webInfo = storage.getCache("webInfo")
            let ApplySupplierPirce = 0
            if (webInfo) {
                ApplySupplierPirce = webInfo.ApplySupplierPirce || 0
            }
            return ApplySupplierPirce
        },
        //更新购物车角标（供应商）
        easyUpSupplierTabBarBadge(data, callBack) {
            this.setSupplierCartData = []
            if (data) {
                this.setSupplierCartData = data
            } else {
                this.setSupplierCartData = this.getSupplierCartData
            }
            getSupplierCartTotal(this.setSupplierCartData, (res) => {
                if (callBack) {
                    callBack(res.totalSpace)
                }
            })
        },
        //跳转页面
        easyGoTo(path) {
            if (!path) {
                return
            }
            let isTab =
                path.includes("/pages/product/index") ||
                path.includes("/pages/me/index") ||
                path.includes("/pages/index/index") ||
                path.includes("/pages/order/index") ||
                path.includes("/pages/cart/index") ||
                path.includes("/pages/supplier/index") ||
                path.includes("/pages/supplier/cart/index") ||
                path.includes("/pages/supplier/order/index")
            if (isTab) {
                // //切换tab页的
                // uni.switchTab({
                // 	url: path
                // });
                if (path.includes("/pages/product/index")) {
                    this.changeHomeTab("product")
                } else if (path.includes("/pages/me/index")) {
                    this.changeHomeTab("me")
                } else if (path.includes("/pages/order/index") || path.includes("/pages/supplier/order/index")) {
                    this.changeHomeTab("order")
                } else if (path.includes("/pages/cart/index") || path.includes("/pages/supplier/cart/index")) {
                    this.changeHomeTab("cart")
                } else if (path.includes("/pages/index/index")) {
                    this.changeHomeTab("home")
                } else if (path.includes("/pages/supplier/index")) {
                    this.changeHomeTab("supplier")
                }
            } else {
                uni.navigateTo({
                    url: path,
                })
            }
        },
        changeHomeTab(tab) {
            eventBus.$emit("CHANGE_TAB", tab)
            this.checkIsGoBack()
        },
        // 不同模式下页面路由
        goOrderPage() {
            let path = "/pages/order/orderPage"
            if (this.getSupplierMode() == 1) {
                //供应商
                path = "/pages/supplier/order/orderPage"
            }
            uni.navigateTo({
                url: path,
            })
        },
        goCartPage(goCartPage) {
            let path = "/pages/cart/cartTemp"
            if (this.getSupplierMode() == 1) {
                //供应商
                path = "/pages/supplier/cart/cartTemp"
            }
            if (goCartPage) {
                // 团购
                path = "/pages/group/cart/index"
            }
            uni.navigateTo({
                url: path,
            })
        },

        //返回首页
        easyGoProduct() {
            this.changeHomeTab("product")
        },
        checkIsGoBack() {
            let pages = getCurrentPages()
            if (pages.length > 1) {
                //回到首页
                uni.navigateBack({
                    delta: getCurrentPages().length,
                })
            }
        },
        easyWebViewGoBack(webView) {
            webView.evalJS("javascript:history.back(-1)")
        },
        //返回上一页
        easyGoBack() {
            uni.navigateBack()
        },
        //返回首页
        easyGoHome() {
            eventBus.$emit("CHANGE_TAB", "home")
            let pages = getCurrentPages()
            if (pages.length > 1) {
                //回到首页
                uni.navigateBack({
                    delta: getCurrentPages().length,
                })
            } else {
                this.easyReLaunchToHome()
            }
        },
        setOffEventForCart() {
            eventBus.$off("SET_CART")
        },
        //清除页面历史栈跳转页面
        easyReLaunchToHome() {
            this.setOffEventForCart()
            uni.reLaunch({
                url: "/pages/index/index",
            })
        },
        //清除页面历史栈跳转页面
        easyReLaunch(path) {
            uni.reLaunch({
                url: path,
            })
        },
        //清除当前页跳转页面
        easyRemoveCurrentGoTo(path) {
            uni.redirectTo({
                url: path,
            })
        },
        //简单toast弹窗提示
        easyToast(msg) {
            uni.showToast({
                title: msg,
                icon: "none",
                duration: 2000,
            })
        },
        //获取颜色值主要给一些不能直接设置css的组件调用
        easyGetColor(color) {
            if (color == "green") {
                return colorCofig.color.green
            }
            if (color == "orange") {
                return colorCofig.color.orange
            }
            if (color == "yellow") {
                return colorCofig.color.yellow
            }
            if (color == "white") {
                return colorCofig.color.white
            }
            if (color == "block") {
                return colorCofig.color.block
            }
            return colorCofig.color.main
        },
        //获取图片拼接全地址
        easyGetImgUrl(url) {
            if (!url || url == "") {
                return "/static/img/no-img.jpg"
            }
            if (url.includes("http")) {
                //全路径直接返回自己
                return url
            }
            return getShopUrls().baseImgUrl + url
        },
        easyGetImgListUrl(url) {
            if (!url || url == "") {
                return this.easyGetImgUrl(url)
            } else if (url.indexOf(",") != -1) {
                let urlArr = url.split(",")
                return this.easyGetImgUrl(urlArr[0])
            } else {
                return this.easyGetImgUrl(url)
            }
        },
        easyImgList(item) {
            if (!item) {
                return ""
            }
            let arr = []
            if (item.indexOf(",") != -1) {
                let urlArr = item.split(",")
                urlArr.forEach((item) => {
                    if (item) {
                        arr.push(this.easyGetImgListUrl(item))
                    }
                })
                return arr
            } else {
                let urlArr = item.split()
                urlArr.forEach((item) => {
                    if (item) {
                        arr.push(this.easyGetImgListUrl(item))
                    }
                })
                return arr
            }
        },
        easyGetUserImgUrl(url) {
            if (url) {
                return this.easyGetImgUrl(url)
            }
            return "/static/img/user-default.jpg"
        },
		//是否能整除包含小数
		isInteger(num1,num2){
			if(num2>num1){
			var max=num2;
			num2=num1;
			num1=max;
			}
			var decimal1=num1.toString().split(".")[1];
			var decimal2=num2.toString().split(".")[1];
			var len1=decimal1?decimal1.length:0;
			var len2=decimal2?decimal2.length:0;
			var len=Math.max(len1,len2);
			return (num1*Math.pow(10,len))%(num2*Math.pow(10,len))==0?true:false;
		},
        //获取当前时间 格式：2021-07-16T09:22:43.998Z
        easyGetTimeForISO() {
            let d = new Date()
            d.setHours(d.getHours(), d.getMinutes() - d.getTimezoneOffset())
            let result = d.toISOString()
            return result
        },
        //获取停留时间
        getStaySeconds(startTime, stopTime) {
            //离开时间 - 进入时间 = 停留时间  取秒
            let stay = new Date(stopTime).getTime() - new Date(startTime).getTime()
            stay = Math.ceil(stay / 1000)
            return stay
        },
        //埋点-页面浏览
        tackVisit(data = null) {
            let userInfo = storage.getCache("userInfo")
            let webInfo = storage.getCache("webInfo")
            if (userInfo && webInfo) {
                let stopTime = this.easyGetTimeForISO()
                //访问页面
                let param = {
                    type: 0,
                    urlTarget: this.tackParam.urlTarget,
                    userID: userInfo.UserId,
                    userName: userInfo.UserName,
                    businessid: webInfo.BusinessId,
                    pageType: gatherType.gatherPageType.page,
                    eventType: gatherType.gatherEventType.visit,
                    startTime: this.tackParam.startTime,
                    stopTime: stopTime,
                    staySeconds: this.getStaySeconds(this.tackParam.startTime, stopTime),
                    title: this.tackParam.pageTitle,
                    eventID: 0,
                }
                if (data) {
                    Object.assign(param, data)
                }
                pagetackinfo(param).then((res) => {
					
				})
            }
        },
        //埋点-提交订单
        tackSubmitOrder(data) {
            this.initTack()
            let param = {
                eventID: data.id || 0,
                eventType: gatherType.gatherEventType.submit,
                orderCount: 1,
                orderPrice: data.orderPrice,
				title:'提交订单'
            }
            this.tackVisit(param)
        },
		//埋点-商品详情 商品ID
		tackProductID(id,title) {
		    let param = {
		        product_ID:id,
				pageType: gatherType.gatherPageType.product,
				title: title,
		    }
		    this.tackVisit(param)
		},
        initTack() {
            //进入时间
            this.tackParam.startTime = this.easyGetTimeForISO()
            //获取标题
            this.tackParam.pageTitle = getNavigationBarTitle()
            //获取标题
            this.tackParam.urlTarget = ""
        },
        openMiniProgram(path, id, appId, type) {
            //#ifdef APP-PLUS
            plus.share.getServices((res) => {
                if (res && res.length > 0) {
                    let sweixin = res.find((e) => {
                        return e.id == "weixin"
                    })
                    //唤醒微信小程序
                    if (sweixin) {
                        if (!id) {
                            //如果没有id 取 默认配置的
                            id = config.payMiniProgram.id
                        }
                        if (!type) {
                            //如果没有type 取 默认配置的
                            type = config.payMiniProgram.type
                        }
                        sweixin.launchMiniProgram({
                            id: id,
                            type: type, //小程序版本  0-正式版； 1-测试版； 2-体验版。
                            path: path,
                        })
                    }
                }
            })

            //#endif
            //#ifdef MP-WEIXIN
            if (!appId) {
                appId = config.payMiniProgram.appId
            }
            uni.navigateToMiniProgram({
                appId: appId,
                path: path,
                success(res) {
                    // 打开成功
                },
                fail(e) {
                    console.log(e)
                },
            })
            //#endif
        },
        getPayIcon(type) {
            let icon = ""
            switch (type) {
                case 0:
                    icon = "/static/img/bank/icon_pay_type_xx.png"
                    break
                case 1:
                    icon = "/static/img/bank/yepay.png"
                    break
                case 2:
                    icon = "/static/img/bank/icon_pay_type_jh.png"
                    break
                case 4:
                case 8:
                case 12:
                case 7:
                case 14:
                    icon = "/static/img/bank/icon_pay_type_wx.png"
                    break
                case 5:
                    icon = "/static/img/bank/icon_pay_type_zfb.png"
                    break
                // case 7:
                // 	icon = '/static/img/bank/icon_pay_type_fuiou.png'
                // 	break;
                // case 8:
                // 	icon = '/static/img/bank/icon_pay_type_yhk.png'
                // 	break;
                case 10:
                    icon = "/static/img/bank/icon_pay_type_xy.png"
                    break
                case 13:
                    icon = "/static/img/bank/icon_pay_type_wx.png"
                    break   
                case 53:
                    icon = "/static/img/bank/icon_pay_type_zfb.png"
                    break       
                default:
                    icon = "/static/img/bank/icon_pay_type_xx.png"
                    break
            }
            return icon
        },
        getOfflinePayTypeIcon(id) {
            switch (id) {
                case 0:
                    return "/static/img/bank/ylpay.png"
                    break
                case 1:
                    return "/static/img/bank/wxpay.png"
                    break
                case 2:
                    return "/static/img/bank/zfbpay.png"
                    break
                case 10:
                    return "/static/img/bank/bank.png"
                    break
                default:
                    return "/static/img/bank/bank.png"
                    break
            }
        },
    },
    //分享
    onShareAppMessage(res) {
		let userInfo = storage.getCache("userInfo")
        return {
            title: this.share.title,
            path: this.share.path+'?tel='+userInfo.Tel,
            imageUrl: this.share.imageUrl,
            desc: this.share.desc,
            content: this.share.content,
            success(res) {
                uni.showToast({
                    title: "分享成功",
                })
            },
            fail(res) {
                uni.showToast({
                    title: "分享失败",
                    icon: "none",
                })
            },
        }
    },
}
